//
//  WBBaseViewController.swift
//  Weibo
//
//  Created by yinbo on 2018/2/27.
//  Copyright © 2018年 yinbo. All rights reserved.
//

import UIKit

class WBBaseViewController: UIViewController {
    
    //访客视图信息字典
    var visitorInfoDic:[String:String]?
    //用户登录标记
//    var  userLogin = false
    var  tableView:UITableView?
    //刷新控件
    var refreshControl:YBRefreshControl?
    //上拉刷新标记
    var isPullup = false
    lazy var bar:UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: 84))
    lazy var navItem = UINavigationItem()
    override var title: String?{
        didSet{
            navItem.title = title
        }
    }
    @objc  func login(){
        print("用户登录")
        NotificationCenter.default.post(name: NSNotification.Name(rawValue:WBUserShouldLoginNotification), object: nil)
        
    }
    @objc  func register(){
    
    }
    
   @objc func loginSuccess(n:Notification){
        print("登录成功")
        //在访问view的getter时，如果view==nil会调用loadview -> viewdidload
        navItem.leftBarButtonItem = nil
        navItem.rightBarButtonItem = nil
        view = nil
    
        //注销通知->重新执行viewdidload会再次注册！避免通知被重复注册
        NotificationCenter.default.removeObserver(self)
    
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        WBNetworkManager.shared.userLogon ? loadData() : ()
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NSNotification.Name(rawValue: WBUserLoginSuccessedNotication), object: nil)
        // Do any additional setup after loading the view.
    }
    deinit {
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    //加载数据-具体实现由子类负责
    func loadData(){
        refreshControl?.endRefreshing()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
//MARK: 设置界面
extension WBBaseViewController{
     func setupUI(){
        //view.backgroundColor = UIColor.cz_random()
        view.backgroundColor = UIColor.white
        //取消自动缩进--如果隐藏了导航栏，会缩进20个点
        automaticallyAdjustsScrollViewInsets = false
        setupnavBar()
        //setupTableView()
        WBNetworkManager.shared.userLogon ? setupTableView() : setupVisitorView()
    }
    //设置访客视图
    private func setupVisitorView(){
        let visitorview = WBVisitorView(frame: view.bounds)
        view.insertSubview(visitorview, belowSubview: bar)
        //visitorview.backgroundColor = UIColor.cz_random()
        
        visitorview.visitorInfo = visitorInfoDic
        visitorview.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside)
        visitorview.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside)
        
        navItem.leftBarButtonItem =  UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(register))
        navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(login))
        //view.addSubview(visitorview)
    }
    func setupTableView(){
        tableView = UITableView(frame: view.bounds, style: .plain)
        view.insertSubview(tableView!, belowSubview: bar)
        tableView?.dataSource = self
        tableView?.delegate = self
//        tableView?.contentInset = UIEdgeInsets(top: bar.bounds.height, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0)
        tableView?.contentInset = UIEdgeInsets(top:20, left: 0, bottom: 0, right: 0)

        //修改指示器的缩进
        tableView?.scrollIndicatorInsets = tableView!.contentInset
        //view.a ddSubview(tableView!)
        refreshControl = YBRefreshControl()
        tableView?.addSubview(refreshControl!)
//        refreshControl?.beginRefreshing()

        refreshControl?.addTarget(self, action:#selector(loadData), for: .valueChanged)
    }
    func setupnavBar(){
        view.addSubview(bar)
        bar.items = [navItem]
        //navbar 的渲染颜色
        bar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6)
        bar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray]
        //设置系统按钮的文字渲染颜色
        bar.tintColor = UIColor.orange
    }
}
//MARK: UITableViewDelegate,UITableViewDataSource

extension WBBaseViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 10
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    //1.在显示最后一行的时候，做上拉刷新
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let row = indexPath.row
        let section = tableView.numberOfSections-1
        
        if row<0||section<0{
            return
        }
        let count = tableView.numberOfRows(inSection: section)
        if row == (count-1) && !isPullup{
            print("上拉刷新")
            isPullup = true
            
            loadData()
        }
    }
}
